/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bifang.business.dao;

import han.bifang.common.entity.SoaRole;
import han.bifang.common.entity.SoaUsergroup;
import han.bifang.common.exception.BifangErrorCode;
import han.bifang.common.exception.BifangException;
import han.bifang.common.persist.dao.DaoManager;
import han.bifang.common.persist.page.Page;
import han.bifang.common.persist.page.PagedQuery;
import han.bifang.common.persist.tx.Tx;
import han.bifang.common.persist.tx.TxManager;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @Author Kent
 */
public class RoleDao {

	public static String createRole(SoaRole role) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			String hql = "from SoaRole s where s.roleName = ?";
			List roles = DaoManager.getDao().find(hql, role.getRoleName());
			if (roles.size() > 0) {
				throw new BifangException(
						BifangErrorCode.ROLE_NAME_EXIST_ERROR, "Role name '"
								+ role.getRoleName() + "' already exists");
			}
			DaoManager.getDao().save(role);
			DaoManager.getDao().flush();
			tx.commit();
			return role.getId();

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(RoleDao.class);
			logger.error("RoleDao.createRole()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"createRole() error", e);
		} finally {
			tx.end();
		}

	}

	public static void modifyRole(SoaRole role) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			String hql = "from SoaRole s where s.roleName = ?";
			List roles = DaoManager.getDao().find(hql, role.getRoleName());
			if (roles.size() > 0) {
				SoaRole u = (SoaRole) roles.get(0);
				if (!u.getId().equals(role.getId()))
					throw new BifangException(
							BifangErrorCode.ROLE_NAME_EXIST_ERROR,
							"Role name '" + role.getRoleName()
									+ "' already exists");
			}
			DaoManager.getDao().merge(role);
			DaoManager.getDao().flush();
			tx.commit();

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(RoleDao.class);
			logger.error("RoleDao.modifyRole()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"modifyRole() error", e);
		} finally {
			tx.end();
		}

	}

	public static SoaRole getRole(String id) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			SoaRole u = (SoaRole) DaoManager.getDao().get(SoaRole.class, id);
			tx.commit();

			return u;
		} catch (Throwable e) {
			Log logger = LogFactory.getLog(RoleDao.class);
			logger.error("RoleDao.getRole()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"getRole() error", e);
		} finally {
			tx.end();
		}

	}

	public static void removeRole(String id) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			SoaRole u = (SoaRole) DaoManager.getDao().get(SoaRole.class, id);
			DaoManager.getDao().delete(u);
			tx.commit();

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(RoleDao.class);
			logger.error("RoleDao.removeRole()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"removeRole() error", e);
		} finally {
			tx.end();
		}

	}

	public static List findRoleByGroupId(String id) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			String hql = "select u  from SoaRole u, SoaUsergroupRoleRel r where r.compId.usergroupId = ?"
					+ " and r.compId.roleId = u.id";
			List ret = DaoManager.getDao().find(hql, id);

			tx.commit();
			return ret;

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(UserDao.class);
			logger.error("RoleDao.findRoleByGroupId()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"findRoleByGroupId() error", e);
		} finally {
			tx.end();
		}

	}
	
	public static List findRolesNotOfGroup(String groupId, String roleName, int page, int pageSize) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			String hql = "from SoaRole sr where sr.id not in (select u.id  from SoaRole u, SoaUsergroupRoleRel r where r.compId.usergroupId = '"
					+ groupId + "' and r.compId.roleId = u.id)";
			if(roleName != null){
				hql += " and sr.roleName like '%" + roleName + "%'";
			}
			
			PagedQuery pq = new PagedQuery(hql,page,pageSize);
			Page p = pq.getPage();
			int total = p.getPaginator().getPageNumber();
			ArrayList ret = new ArrayList();
			ret.add(total);
			ret.add(p.getList());
			tx.commit();
			return ret;

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(UserDao.class);
			logger.error("RoleDao.findRolesNotOfGroup()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"findRolesNotOfGroup() error", e);
		} finally {
			tx.end();
		}

	}
	
	public static List findRoleByUserId(String id) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			String hql = "select u  from SoaRole u, SoaUserRoleRel r where r.compId.userId = ?"
					+ " and r.compId.roleId = u.id";
			List ret = DaoManager.getDao().find(hql, id);

			tx.commit();
			return ret;

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(UserDao.class);
			logger.error("RoleDao.findRoleByUserId()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"findRoleByUserId() error", e);
		} finally {
			tx.end();
		}

	}
	
	public static List findRoleByResId(String id) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			String hql = "select u  from SoaRole u, SoaRoleResRel r where r.compId.resId = ?"
					+ " and r.compId.roleId = u.id";
			List ret = DaoManager.getDao().find(hql, id);

			tx.commit();
			return ret;

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(UserDao.class);
			logger.error("RoleDao.findRoleByResId()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"findRoleByResId() error", e);
		} finally {
			tx.end();
		}

	}
	
	public static List findRolesNotOfResource(String resourceId, String roleName, int page, int pageSize) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			String hql = "from SoaRole sr where sr.id not in (select u.id  from SoaRole u, SoaRoleResRel r where r.compId.resId = '"
					+ resourceId + "' and r.compId.roleId = u.id)";
			if(roleName != null){
				hql += " and sr.roleName like '%" + roleName + "%'";
			}
			
			PagedQuery pq = new PagedQuery(hql,page,pageSize);
			Page p = pq.getPage();
			int total = p.getPaginator().getPageNumber();
			ArrayList ret = new ArrayList();
			ret.add(total);
			ret.add(p.getList());
			tx.commit();
			return ret;

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(UserDao.class);
			logger.error("RoleDao.findRolesNotOfGroup()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"findRolesNotOfGroup() error", e);
		} finally {
			tx.end();
		}

	}
	
	public static List findRolesByPage(String roleName, int page,
			int pageSize) throws BifangException {
		Tx tx = null;

		try {
			tx = TxManager.start();
			
			String hql = "from SoaRole u where 1 = 1";
			if(roleName != null){
				hql = hql + " and u.roleName like '%" + roleName + "%'";
			}
			
			PagedQuery pq = new PagedQuery(hql,page,pageSize);
			Page p = pq.getPage();
			int total = p.getPaginator().getPageNumber();
			ArrayList ret = new ArrayList();
			ret.add(total);
			ret.add(p.getList());
			tx.commit();

			
			return ret;

		} catch (Throwable e) {
			Log logger = LogFactory.getLog(UserDao.class);
			logger.error("UserDao.findGroupsByPage()", e);
			tx.rollback();
			throw new BifangException(BifangErrorCode.DB_ERROR,
					"findGroupsByPage() error", e);
		} finally {
			tx.end();
		}
	}
	
}
